package com.qf.service.impl;

import com.qf.service.DocService;
import com.qf.util.ConnectionUtil;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

/*
杨威
2022/1/17
22:08
*/
public class DocServiceImpl implements DocService {
    public void addDoc(String index, String source) throws IOException {
        RestHighLevelClient client = ConnectionUtil.getClient();
        IndexRequest indexRequest = new IndexRequest(index);
        indexRequest.source(source, XContentType.JSON);
        IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println("response = " + response);
    }

    //新增 自定义id
    public void addDocWithId(String index, String id, String source) throws IOException {

        RestHighLevelClient highLevelClient = ConnectionUtil.getClient();
        IndexRequest indexRequest = new IndexRequest(index);
        indexRequest.id(id);//手动设置id
        indexRequest.source(source, XContentType.JSON);//设置要添加的数据以及格式为json
        IndexResponse response = highLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        System.err.println(response.toString());
    }
//修改document
    public void updateDoc(String index, String id, String source) throws Exception {
        RestHighLevelClient highLevelClient = ConnectionUtil.getClient();
        UpdateRequest updateRequest = new UpdateRequest(index, id);//设置要更新的库和id
        updateRequest.doc(source, XContentType.JSON);//设置要更新的内容
        UpdateResponse response = highLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        System.err.println(response.toString());
    }

    //根据id删除document
    public void deleteDoc(String index, String id) throws Exception {
        RestHighLevelClient highLevelClient = ConnectionUtil.getClient();
        DeleteRequest deleteRequest = new DeleteRequest(index, id);
        DeleteResponse response = highLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        System.err.println(response.toString());
    }
}
